/**
 * 存储数据到 LocalStorage
 * @param key storage key
 * @param value storage value
 */
export function setLocalStorage(key: string, value?: string) {
  if (value === undefined) {
    localStorage.removeItem(key);
    return;
  }

  localStorage.setItem(key, value);
}

export function setBooleanLocalStorage(key: string, value?: boolean) {
  if (value === undefined) {
    setLocalStorage(key);
    return;
  }
  setLocalStorage(key, value ? 'true' : 'false');
}

/**
 * 存储数据到 SessionStorage
 * @param key storage key
 * @param value storage value
 */
export function setSessionStorage(key: string, value?: string) {
  if (value === undefined) {
    sessionStorage.removeItem(key);
    return;
  }

  sessionStorage.setItem(key, value);
}

export function setBooleanSessionStorage(key: string, value?: boolean) {
  if (value === undefined) {
    setSessionStorage(key);
    return;
  }
  setSessionStorage(key, value ? 'true' : 'false');
}

/**
 * 从 LocalStorage 中获取数据
 * @param key storage key
 * @returns 无数据返回 undefined
 */
export function getLocalStorage(key: string) {
  return localStorage.getItem(key) || undefined;
}


/**
 * 从 SessionStorage 中获取数据
 * @param key storage key
 * @returns 无数据返回 undefined
 */
export function getSessionStorage(key: string) {
  return sessionStorage.getItem(key) || undefined;
}

export function getSessionStorageToBoolean(key: string, defaultValue = false) {
  const val = getSessionStorage(key);
  return val !== undefined ? val === 'true' : defaultValue;
}


export function getLocalStorageToBoolean(key: string, defaultValue = false) {
  const val = getLocalStorage(key);
  return val !== undefined ? val === 'true' : defaultValue;
}

export function getLocalStorageToList<T>(key: string): T[] | undefined {
  const res = getLocalStorage(key);
  if (!res) {
    return;
  }
  return JSON.parse(res);
}

export function getLocalStorageToNumber(key: string, defaultValue = 0): number {
  const val = getLocalStorage(key);

  if (val === undefined) {
    return defaultValue;
  }

  const num = Number(val);

  if (Number.isNaN(num)) {
    return defaultValue;
  }

  return num;
}